package com.zrb.mobile;

import org.apache.http.Header;
import org.json.JSONArray;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.mobile.ui.CenterProgressWebView.IOnJsPrompt;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.checkCollection;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ZrbRestClient;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MoneyDetailActivity extends BaseCheckloginActivity implements
		OnClickListener, onCollectionListener, checkCollection, IOnJsPrompt {

	private Long curfindmoneyId;
	boolean isFavorite = false;
	Dialog AuthDialog;
	TextView btnfavorite;
	CollectionHelper mCollectionHelper;
	CenterProgressWebView mWebView;
	String title;
	private int postion = -1;
	// public String ACTION_NAME_FIVE = "find_money";
	// public String ACTION_NAME_FOUR = "discover_detail_content";
	// public String ACTION_NAME_THREE = "my_publish";
	// public String ACTION_NAME_SIX = "user_my_findmoney";
	private int position;
	private String from;
	
	public static void launch (Context mActivity,long id,String title){
		
		 if(mActivity==null) return;
		 Intent it = new Intent(mActivity, MoneyDetailActivity.class);
		 it.putExtra("id", id );
		 it.putExtra("title", title );
		  mActivity.startActivity(it);
	}
	

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.news_web_content);

		if (bundle != null)
			restoreSelf(bundle);
		else {
			curfindmoneyId = this.getIntent().getLongExtra("id", -1);
			title = this.getIntent().getStringExtra("title");
			from = this.getIntent().getStringExtra("from");
			position = this.getIntent().getIntExtra("position", -1);
		}
		init();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong("newid", curfindmoneyId);
		outState.putString("title", title);
		outState.putString("from", from);
		outState.putInt("position", position);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		curfindmoneyId = savedInstanceState.getLong("newid");
		title = savedInstanceState.getString("title");
		from = savedInstanceState.getString("from");
		position = savedInstanceState.getInt("position");
	}

	private void init() {

		mCollectionHelper = new CollectionHelper(this, Constants.FocusMoney);
		mCollectionHelper.setOnCollectionListener(this);
		mCollectionHelper.setOncheckCollection(this);

		this.findViewById(R.id.title_left_root).setOnClickListener(this);
		this.findViewById(R.id.btn_share).setOnClickListener(this);
		this.findViewById(R.id.btn_font).setOnClickListener(this);

		btnfavorite = (TextView) this.findViewById(R.id.btn_favorite);
		btnfavorite.setVisibility(View.VISIBLE);
		btnfavorite.setOnClickListener(this);

		mWebView = (CenterProgressWebView) this.findViewById(R.id.webView1);
		mWebView.setOnPageListener(null);
		// mWebView.addJavascriptInterface(this, "localApi");
		mWebView.setOnJsPromptListener(this);
		// http://backend.zhaorongbao.com:8090/newsapp/newsDetails?id=26
		// String url="file:///android_asset/detail/detail.html";
		String url = AppSetting.BASE_URL + "fund/detail?id=" + curfindmoneyId;
		mWebView.loadUrl(url);

		if (AppSetting.curUser != null)
			mCollectionHelper.checkCollect(curfindmoneyId);
	}

	@Override
	public void onCollectionEvent() {
		// TODO Auto-generated method stub
		// showToast(!isFavorite ?"已关注":"取消关注", Project_info_lience.this);
		isFavorite = !isFavorite;
		btnfavorite.setSelected(isFavorite);
		btnfavorite.setText(isFavorite ? "已关注" : "关 注");
		btnfavorite.setEnabled(false);
		if ("1".equals(from)) {
			Intent intent1 = new Intent(
					Constants.FocusNum_MONEYDETIALS_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		} else if ("2".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_PUBLISE_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		} else if ("3".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_MYMONEY_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		}else if (Constants.DETAIL_TYPE.equals(from)) {
			Intent intent1 = new Intent(Constants.MONNum_ATTENTION_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		}
//		else if ("5".equals(from)) {
//			Intent intent1 = new Intent(Constants.FocusNum_Find_mainlist);
//			intent1.putExtra("from", "1");
//			intent1.putExtra("position", position);
//			intent1.putExtra("attention", isFavorite ? 1 : 0);
//			sendBroadcast(intent1);
//		}
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				btnfavorite.setEnabled(true);
			}

		}, 2000);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_left_root:
			if (mWebView.canGoBack()) {
				mWebView.goBack();
				return;
			}
			;
			this.finish();
			break;
		case R.id.btn_share:
			shareLink();
			break;
		case R.id.btn_favorite:
			if (AppSetting.curUser == null) {
				showLoginDialog();
			} else {
				mCollectionHelper.onClickCollect(curfindmoneyId, !isFavorite);
			}
			break;
		case R.id.btn_font:
			callServerPhone();
			break;
		default:
			break;
		}
	}

	private void shareLink() {
		// String imageLink=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
		Intent intent = new Intent(MoneyDetailActivity.this,
				News_ShareActivity.class);
		intent.putExtra("title", title);
		// intent.putExtra("url",imageLink);
		intent.putExtra("url", mWebView.getUrl());
		startActivity(intent);
	}

	public void callServerPhone() {
		DialogBuilder builder2 = new DialogBuilder(MoneyDetailActivity.this);
		// builder2.setTheme(Resource.Style.customDialog);
		builder2.setParentlayout(R.layout.custom_ucenter_dialog);
		builder2.setContentView(R.layout.u_center_org_auth); // ac_dialog_cancel;
		builder2.setPositiveTitle("呼叫");
		TextView hitetxt = (TextView) builder2.getCurContentView()
				.findViewById(R.id.tv_authstr);
//		String msource = this.getResources().getString(
//				R.string.user_center_profile_edit_org_authtrue1);
//		hitetxt.setText(msource);
		hitetxt.setText(Constants.serverPhone);
		builder2.setCloseOnclick(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AuthDialog.dismiss();
				if (arg0.getId() == R.id.btn_confirm) {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri
							.parse("tel:" + Constants.serverPhone));// "400-688-0101"
					MoneyDetailActivity.this.startActivity(intent);
				}
			}
		});
		AuthDialog = builder2.create();
		AuthDialog.show();
	}

	@Override
	public void onhasCollection(boolean ishas) {
		// TODO Auto-generated method stub
		isFavorite = ishas;
		btnfavorite.setSelected(isFavorite);
		btnfavorite.setText(isFavorite ? "已关注" : "关 注");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			switch (requestCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
			case 500:
				if (AppSetting.curUser != null)
					mCollectionHelper.checkCollect(curfindmoneyId);
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void PromptInfo(String message, String defaultValue) {
		// TODO Auto-generated method stub
		Log.e("PromptInfo", message);//id
		if(TextUtils.isEmpty(message)) return;
		if(!message.contains(",")) return;
		//CommonUtil.showToast(message+"|"+defaultValue, this);
		 String[] tmpArr=message.split(",");
 
		  if("4".equals(tmpArr[0])){
			  imageBrower();
	      }
	}

	private void imageBrower() {
 		 ZrbRestClient.get("fund/getPhotoList?id="+curfindmoneyId , null,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3) {
							CommonUtil.showToast("网络超时,请重新连接");
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// TODO Auto-generated method stub
							String results = new String(arg2);
							try {
								
								   JSONArray jsonObject2 =new JSONArray(results);
							 
								   String[] urls=new String[jsonObject2.length()];
								   String[] picdes= new String[jsonObject2.length()];
 						     	   for(int i=0;i<jsonObject2.length();i++){
 						     		  urls[i]=AppSetting.mediaServer+"/"+jsonObject2.getJSONObject(i).getString("url");
 						     	      picdes[i]=jsonObject2.getJSONObject(i).getString("remark"); 
  						     	   }
 						     		
								 
 						     	   Intent intent = new Intent(MoneyDetailActivity.this, ImagePagerActivity.class);
 						     	   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
 						        	intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INFOS, picdes);
 								   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
 								   startActivity(intent);
						        } catch (Exception e) {
								   CommonUtil.showToast("服务端数据异常");//fail:"+e.getMessage()
							    }
						}
					});
	}
	
	
	@Override
	public void ReceivedTitle(String title) {
		// TODO Auto-generated method stub
		
	}
}
